using System;
using System.Collections.Generic;
using System.Text;
using System.Web.UI;
using ARF.Web.Interfaces;
using System.Xml.XPath;
using System.Xml;
using System.Collections.Specialized;
using System.Web;
using Microsoft.SharePoint;
using ARF.Web.Fields;
using Microsoft.SharePoint.WebControls;

namespace ARF.Web.Controls
{
    public class XmlProvider : TemplateControl, IXmlProvider
    {
        private IXPathNavigable _xmlDocument;
        private XslRenderControl _xslRender;

        public virtual XslRenderControl Xsl
        {
            get
            {
                if (_xslRender == null)
                {
                    _xslRender = XslRenderControl.Create(this);
                    _xslRender.ID = ID + "_XSL";
                }
                return _xslRender;
            }

            set { _xslRender = value; }
        }

        protected SPWeb Web
        {
            get { return SPContext.Current.Web; }
        }

        public SPControlMode FormMode
        {
            get { return SPContext.Current.FormContext.FormMode; }
        }

        public bool IsEditingPostback
        {
            get { return ARFProperties.Current.IsEditingPostback; }
        }

        protected override void Render(HtmlTextWriter writer)
        {
            if (!Xsl.IsCached) 
                Xsl.XmlObject = XmlAsObject;

            RenderChildren(writer);

            Xsl.RenderControl(writer);
        }

        protected NameValueCollection QueryString
        {
            get
            {
                return HttpContext.Current.Request.QueryString;
            }
        }

        #region IXmlProvider Members

        public IXPathNavigable XmlAsObject
        {
            get
            {
                EnsureXml();
                return _xmlDocument;
            }
            set
            {
                _xmlDocument = value;
            }
        }

        public string XmlAsString
        {
            get
            {
                if (_xmlDocument is XmlDocument)
                    return ((XmlDocument)_xmlDocument).OuterXml;

                return "";
            }
            set
            {
                XmlDocument oDoc = new XmlDocument();
                oDoc.LoadXml(value);
                _xmlDocument = oDoc;
            }
        }

        #endregion

        protected void EnsureXml()
        {
            if (_xmlDocument == null) BuildXml();
        }

        protected virtual void BuildXml()
        {
            try
            {
                XmlAsString = "<Empty>Ensure you override BuildXml()</Empty>";
            }
            catch (Exception ex)
            {
                Log.Trace(ex);
            }
        }

    }
}
